﻿using Dyd.BaseService.ConfigManager.Domain;
using Dyd.BaseService.ConfigManager.Domain.Dal;
using Dyd.BaseService.ConfigManager.Domain.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Webdiyer.WebControls.Mvc;
using XXF.Db;
using System.Linq;
using XXF.Extensions;
using Dyd.BaseService.ConfigManager.Web.Tools;

namespace Dyd.BaseService.ConfigManager.Web.Controllers
{
    [Authorize]
    public class ConfigController : Controller
    {
        private tb_log_dal logDal = new tb_log_dal();
        tb_failover_dal failOverDal = new tb_failover_dal();
        tb_loadbalance_dal loadBalanceDal = new tb_loadbalance_dal();
        private tb_config_dal configDal = new tb_config_dal();
        private tb_category_dal categoryDal = new tb_category_dal();
        #region 列表
        public ActionResult ConfigIndex(DateTime? startTime, DateTime? endTime, int categoryid = 0, string configkey = "", string configvalue = "", string remark = "", int pageIndex = 1, int pageSize = 20)
        {
            if (startTime != null)
            {
                startTime = startTime.Value;
            }
            else
            {
                startTime = DateTime.Now.AddDays(-30);
            }
            if (endTime != null)
            {
                endTime = endTime.Value;
            }
            else
            {
                endTime = DateTime.Now.AddDays(1);
            }
            ViewBag.startTime = startTime;
            ViewBag.endTime = endTime;
            ViewBag.CategoryId = categoryid;
            ViewBag.Configkey = configkey;
            ViewBag.Configvalue = configvalue; ViewBag.remark = remark;
            int count = 0;
            using (DbConn conn = DbConfig.CreateConn(DataConfig.ConfigMangeConnectString))
            {
                conn.Open();
                List<SelectListItem> ddlList = new List<SelectListItem>();
                ddlList.Add(new SelectListItem { Text = "全部", Value = "0" });

                var categoryList = categoryDal.GetList(conn);
                foreach (var item in categoryList)
                {
                    var selected = categoryid == item.id;
                    ddlList.Add(new SelectListItem { Text = item.name, Value = item.id.ToString(), Selected = selected });
                }
                ViewBag.Category = ddlList;

                IList<tb_config_model> list = configDal.GetPageList(conn, startTime, endTime, categoryid, configkey, configvalue, remark, pageSize, pageIndex, ref count);
                PagedList<tb_config_model> pageList = new PagedList<tb_config_model>(list, pageIndex, pageSize, count);
                if (Request.IsAjaxRequest())
                {
                    return PartialView("_ConfigIndex", pageList);
                }
                else
                {
                    return View(pageList);
                }
            }
        }
        #endregion

        #region 新增
        public ActionResult ConfigAdd()
        {
            using (DbConn conn = DbConfig.CreateConn(DataConfig.ConfigMangeConnectString))
            {
                conn.Open();
                List<SelectListItem> list = new List<SelectListItem>();

                var categoryList = categoryDal.GetList(conn);
                foreach (var item in categoryList)
                {
                    list.Add(new SelectListItem { Text = item.name, Value = item.id.ToString() });
                }
                ViewBag.Category = list;
                return View();
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult ConfigAdd(tb_config_model model, string loadBalance, string failLoad, string loadBalanceSwitch, string failOverSwitch)
        {
            List<tb_failover_model> failoverList = JsonConvert.DeserializeObject<List<tb_failover_model>>(failLoad);
            List<tb_loadbalance_model> loadBalanceList = JsonConvert.DeserializeObject<List<tb_loadbalance_model>>(loadBalance);

            model.configkey = model.configkey ?? "";
            model.configvalue = model.configvalue.NullToEmpty();

            for (int i = 0, length = failoverList.Count; i < length; i++)
            {
                failoverList[i].sequence = Convert.ToInt16(i + 1);
            }

            for (int i = 0, length = loadBalanceList.Count; i < length; i++)
            {
                loadBalanceList[i].sequence = Convert.ToInt16(i + 1);
            }

            if (!string.IsNullOrEmpty(failOverSwitch))
            {
                if (failoverList.Count > 0)
                {
                    model.failoversequence = failoverList.OrderByDescending(s => s.id).FirstOrDefault().id;
                }
            }
            else
            {
                model.failoversequence = -1;
            }

            if (!string.IsNullOrEmpty(loadBalanceSwitch))
            {
                model.loadbalancealgorithmenum = 1;
            }
            else
            {
                model.loadbalancealgorithmenum = -1;
            }

            using (DbConn conn = DbConfig.CreateConn(DataConfig.ConfigMangeConnectString))
            {
                try
                {
                    conn.Open();

                    if (configDal.IsExist(conn, model))
                    {
                        return Json(new OperateResults { Flag = false, Message = "当前分类下配置Key重复！" }, JsonRequestBehavior.AllowGet);
                    }
                    conn.BeginTransaction();
                    model.createtime = conn.GetServerDate();
                    model.lastupdatetime = conn.GetServerDate();
                    var id = configDal.Add(conn, model, failoverList, loadBalanceList);
                    RedisHelper.SendCommand(new XXF.BaseService.ConfigManager.SystemRuntime.ConfigNetCommand()
                    {
                        CategoryID = model.categoryid,
                        CommandType = XXF.BaseService.ConfigManager.SystemRuntime.EnumCommandType.ConfigUpdate,
                        ProjectName = ""
                    });
                    conn.Commit();

                    logDal.Add(conn, string.Format("{0}|id:{1}|key:{2}|value:{3}", "添加配置", id, model.configkey, model.configvalue), "", model.categoryid);
                    return Json(new OperateResults { Flag = true, Message = "添加成功！" }, JsonRequestBehavior.AllowGet);
                }
                catch (Exception exp)
                {
                    conn.Rollback();
                    return Json(new OperateResults { Flag = false, Message = exp.Message }, JsonRequestBehavior.AllowGet);
                }
            }
        }
        #endregion

        #region 修改
        public ActionResult ConfigEdit(int id)
        {
            using (DbConn conn = DbConfig.CreateConn(DataConfig.ConfigMangeConnectString))
            {
                conn.Open();
                List<SelectListItem> list = new List<SelectListItem>();

                var categoryList = categoryDal.GetList(conn);
                foreach (var item in categoryList)
                {
                    list.Add(new SelectListItem { Text = item.name, Value = item.id.ToString() });
                }
                ViewBag.Category = list;

                var model = configDal.Get(conn, id);
                ViewBag.LoadBalanceList = loadBalanceDal.GetListByConfigId(conn, id);
                ViewBag.FailOverList = failOverDal.GetListByConfigId(conn, id);
                return View(model);
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public JsonResult ConfigEdit(tb_config_model model, string loadBalance, string failLoad, string loadBalanceSwitch, string failOverSwitch)
        {
            List<tb_failover_model> failoverList = JsonConvert.DeserializeObject<List<tb_failover_model>>(failLoad);
            List<tb_loadbalance_model> loadBalanceList = JsonConvert.DeserializeObject<List<tb_loadbalance_model>>(loadBalance);
            model.configkey = model.configkey ?? "";
            model.configvalue = model.configvalue.NullToEmpty();
            for (int i = 0, length = failoverList.Count; i < length; i++)
            {
                failoverList[i].sequence = Convert.ToInt16(i + 1);
            }

            for (int i = 0, length = loadBalanceList.Count; i < length; i++)
            {
                loadBalanceList[i].sequence = Convert.ToInt16(i + 1);
            }

            if (!string.IsNullOrEmpty(failOverSwitch))
            {
                if (failoverList.Count > 0)
                {
                    model.failoversequence = failoverList.OrderByDescending(s => s.id).FirstOrDefault().id;
                }
            }
            else
            {
                model.failoversequence = -1;
            }

            if (!string.IsNullOrEmpty(loadBalanceSwitch))
            {
                model.loadbalancealgorithmenum = 1;
            }
            else
            {
                model.loadbalancealgorithmenum = -1;
            }
            using (DbConn conn = DbConfig.CreateConn(DataConfig.ConfigMangeConnectString))
            {
                try
                {
                    conn.Open();
                    if (configDal.IsExist(conn, model))
                    {
                        return Json(new OperateResults { Flag = false, Message = "当前分类下配置Key重复！" }, JsonRequestBehavior.AllowGet);
                    }
                    conn.BeginTransaction();
                    model.createtime = conn.GetServerDate();
                    model.lastupdatetime = conn.GetServerDate();
                    configDal.Edit(conn, model, failoverList, loadBalanceList);
                    RedisHelper.SendCommand(new XXF.BaseService.ConfigManager.SystemRuntime.ConfigNetCommand()
                    {
                        CategoryID = model.categoryid,
                        CommandType = XXF.BaseService.ConfigManager.SystemRuntime.EnumCommandType.ConfigUpdate,
                        ProjectName = ""
                    });
                    conn.Commit();
                    logDal.Add(conn, string.Format("{0}|id:{1}|key:{2}|value:{3}", "修改配置", model.id, model.configkey, model.configvalue), "", model.categoryid);

                    return Json(new OperateResults { Flag = true, Message = "修改成功！" }, JsonRequestBehavior.AllowGet);
                }
                catch (Exception exp)
                {
                    conn.Rollback();
                    return Json(new OperateResults { Flag = false, Message = exp.Message }, JsonRequestBehavior.AllowGet);

                }
            }
        }
        #endregion

        #region 删除
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult ConfigDel(int id)
        {
            using (DbConn conn = DbConfig.CreateConn(DataConfig.ConfigMangeConnectString))
            {
                try
                {
                    conn.Open();
                    conn.BeginTransaction();
                    var model = configDal.Get(conn, id);
                    configDal.Delete(conn, id);
                    failOverDal.DeleteByConfigId(conn, id);
                    loadBalanceDal.DeleteByConfigId(conn, id);
                    RedisHelper.SendCommand(new XXF.BaseService.ConfigManager.SystemRuntime.ConfigNetCommand()
                    {
                        CategoryID = model.categoryid,
                        CommandType = XXF.BaseService.ConfigManager.SystemRuntime.EnumCommandType.ConfigReload,
                        ProjectName = ""
                    });
                    conn.Commit();
                    logDal.Add(conn, string.Format("{0}|id:{1}|key:{2}", "删除配置", id, model.configkey, model.configvalue), "", model.categoryid);
                    return Json(new OperateResults { Flag = true, Message = "删除成功！" });
                }
                catch (Exception exp)
                {
                    conn.Rollback();
                    return Json(new OperateResults { Flag = false, Message = exp.Message });
                }
            }
        }
        #endregion


    }
}
